<?php
namespace app\admin\controller;

use think\Db;
use app\admin\model\Orders;

class Order extends Common {

	private $db = null;
	private $config = '';
	private $default_config = '';
	private $oto_db_prefix = ''; //oto平台数据库名和表前缀
	private $pt_table_prefix = ''; //跑腿平台表前缀
	private $orderField = '';
	protected function _initialize(){
		parent::_initialize();
		$this->config = config('database.db_config');
		$this->default_config = config('database');
		$this->oto_db_prefix = $this->config['database'].'.'.$this->config['prefix'];
		$this->pt_table_prefix = config('database.prefix');
		$this->db = Db::connect($this->config);
		$this->orderField = array('o.orderId','o.shopId','o.orderNo','o.orderStatus','o.totalMoney','o.deliverMoney','o.deliverNo','o.payType','o.isPay','o.userId','o.userName','o.userAddress','o.userPhone','o.orderRemarks','o.areaId1','o.areaId2','o.areaId3','o.orderFlag','o.requireTime','o.createTime');
	}
	
	public function test(){
// 		$data = Db::query("select * from {$this->oto_db_prefix}users ou left join {$this->pt_table_prefix}user u on ou.userId=u.id where u.id=11");
// 		p(db()->getLastSql());
// 		p($data);
	}
	
	private function query_where(){
		$params = array();
		if (!empty($_REQUEST)){
			$params = $_REQUEST;
			unset($params['page']);
		}
		$map = "o.pickup=0 and o.isSelf=0 and o.orderStatus=1";
		$userPhone = input('get.userPhone');
		$timestamp = input('get.timestamp');
		if ($userPhone) $map .= " and userPhone='{$userPhone}'";
		$selected1 = $selected2 = $selected3 = false;
		switch ($timestamp) {
			case 5:
				$timestamp = date('Y-m-d H:i:s',time() - 5*60);
				$map .= " and o.createTime > '{$timestamp}'";
				$selected1 = true;
				break;
			case 10:
				$start_timestamp = date('Y-m-d H:i:s',time() - 5*60);
				$end_timestamp = date('Y-m-d H:i:s',time() - 10*60);
				$map .= " and o.createTime > '{$start_timestamp}' and o.createTime < '{$end_timestamp}'";
				$selected2 = true;
				break;
			case 11:
				$start_timestamp = date('Y-m-d H:i:s',time() - 10*60);
				$map .= " and o.createTime < '{$start_timestamp}'";
				$selected3 = true;
				break;
		}
		return array('params' => $params,'map' => $map,'selected1' => $selected1,'selected2' => $selected2,'selected3' => $selected3);
	}
	
	//未接单列表
	public function index(){
		$query_where = $this->query_where();
 		$data = $this->db->name('orders as o')->where($query_where['map'])->field($this->orderField)
		->order('createTime desc')->paginate(config('page_size'), false, array('query' => $query_where['params']));
		// dump($data);
		$this->assign('lists',$data);
		$this->assign('page',$data->render());
		$this->assign('userPhone',input('get.userPhone'));
		$this->assign('selected1',$query_where['selected1']);
		$this->assign('selected2',$query_where['selected2']);
		$this->assign('selected3',$query_where['selected3']);
		return $this->fetch();
	}
	
	//接单未取餐列表
	public function index2(){
		$query_where = $this->query_where();
		$where = 'do.time > 0';
		$where = $this->query_string($where);
		$this->orderField = implode(',', $this->orderField).',do.id,do.userId as delivery_uid,do.deliverMoney,do.time,do.timeout,do.iscount';
		$totalRow = current(Db::query("SELECT COUNT(do.id) AS count FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.status=0 and $where"));
		$totalPage = ceil($totalRow['count']/2);
		$data = Db::query("SELECT {$this->orderField} FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.status=0 and $where");
		$this->user($data);
		$this->assign('lists',$data);
		$this->assign('page','');
		return $this->fetch('index2');
	}

	private function user($data){
		$uids = array();
		foreach ($data as $key => $value){
			if (!in_array($value['delivery_uid'], $uids) && $value['delivery_uid'] != 0){
				$uids[] = $value['delivery_uid'];
			}
		}
		//$uids = array_unique($uids);
		$user = db('user')->where(array('id' => array('IN',$uids)))->field(array('id','username','mobile','truename'))->select();
		$users = array();
		foreach ($user as $key => $value){
			$users[$value['id']] = $value;
		}
		unset($user);
		$this->assign('user',$users);
	}
	
	private function query_string($where){
		$userPhone = $this->request->get('userPhone');
		$account = $this->request->get('account');
		$timeout = $this->request->get('timeout');
		$countstatus = $this->request->get('countstatus');
// 		$where = 'do.time > 0';
		if ($userPhone != '') $where .= " and o.userPhone='{$userPhone}'";
		if ($timeout) $where .= " and do.timeout='{$timeout}'";
		if ($countstatus) $where .= " and do.iscount='{$countstatus}'";
		if ($account != ''){
			if (_checkmobile($account)){
				$map = array('mobile' => $account);
			}else{
				$map = array('truename' => $account);
			}
			$user = db('user')->where($map)->find();
			if (empty($user)) $this->error('配送员账号/姓名不存在');
			$where .= " and do.userId='{$user['id']}'";
		}
		$this->assign('userPhone',$userPhone);
		$this->assign('selected',$timeout);
		$this->assign('countstatus',$countstatus);
		$this->assign('account',$account);
		return $where;
	}
	
	public function notcount(){
		$order_id = intval($this->request->get('orderid'));
		if (!$order_id) $this->error('操作失败');
		$order = db('delivery_order')->where(array('id' => $order_id))->find();
		$this->assign('not_layout',true);
		$this->assign($order);
		$issue = db('issue')->select();
		$this->assign('issue',$issue);
		$isData = db('user_msg')->where(array('orderid' => $order_id))->find();
		$this->assign('isData',$isData);
		return $this->fetch('notcount');
	}
	
	public function run_user(){
		if (!request()->isAjax()) $this->error('操作失败');
		$order_id = intval($this->request->post('orderId'));
		$user_id = intval($this->request->post('user_id'));
		$issue = db('issue')->where(array('id' => $this->request->post('type')))->find();
		//$issue['type'] 1: 订单不结算配送原因 2: 更换配送员原因
		$data = array(
			'orderid' => $order_id,
			'type' => $this->request->post('type'),
			'uid' => $this->request->post('uid'),
			'admin_uid' => $this->userinfo['id'],
			'content' => $this->request->post('content'),
			'status' => 0,
			'time' => time(),
		);
		$order = db('delivery_order')->where(array('orderId' => $order_id,'user_send' => 0))->find();
		if ($user_id == $order['userId']){
			$this->ajaxReturn(array('code' => 0,'msg' => '请选择一个新的配送员'));
		}
		if ($data['content'] == '') $this->ajaxReturn(array('code' => 0,'msg' => '请输入消息内容'));
		if (!$user_id) $this->ajaxReturn(array('code' => 0,'msg' => '请选择配送员'));
		$user = db('user')->where(array('id' => $user_id,'status' => 1,'check_status' => 1))->field(array('id','mobile'))->find();
		if (empty($user)) $this->ajaxReturn(array('code' => 0,'msg' => '配送员不存在'));
		if ($issue['type'] == 1){
			db('delivery_order')->where(array('id' => $order_id))->setField('iscount',2);
		}else{
			db('delivery_order')->where(array('id' => $order_id))->setField('timeout',2);
		}
	
		db('delivery_order')->where(array('id' => $order['id']))->setField('userId',$user_id);
	
		if (db('user_msg')->insert($data)){
			$this->ajaxReturn(array('code' => 1,'msg' => '操作成功'));
		}else{
			$this->ajaxReturn(array('code' => 0,'msg' => '操作失败'));
		}
	}
	
	public function updateuser(){
		$this->assign('not_layout',true);
		$orderId = $this->request->param('orderid');
		if (!$orderId) $this->error('订单不存在');
		$order = db('delivery_order')->where(array('id' => $orderId))->find();
		$this->assign($order);
		$orderId = $order['orderId'];
		$orderInfo = $this->db->name('orders')->where(array('orderId' => $orderId))->find();
		if (!$orderInfo) $this->error('订单不存在');
// 		//派单平台设置商家配送区域
// 		$shop_section = db('set_section')->where(array('shopId' => $orderInfo['shopId']))->find();
// 		//符合的配送员和配送地区
// 		$user = db('user_section')->where(array('section_id' => array('in',$shop_section['section'])))->select();
// 		$userids = '';
// 		$address_ids = array();
// 		foreach ($user as $key => $value){
// 			$address_ids[] = $value['section_id'];
// 			$userids .= $value['uid'].',';
// 		}
// 		$address_section = array();
// 		if (!empty($userids)){
// 			$address_section = db('address_section')->where(array('id' => array('IN',$address_ids)))->select();
// 		}
		$address_section = db('address_section')->select();
		
		//$userlists = db('user')->where(array('status' => 1,'check_status' => 1,'id' => array('IN',rtrim($userids,','))))->field(array('id','username','truename','mobile','user_face'))->select();
		$userlists = db('user')->where(array('status' => 1,'check_status' => 1))->field(array('id','username','truename','mobile','user_face'))->select();
		$this->assign('userlist',$userlists);
		$this->assign('orderInfo',$orderInfo);
		$issue = db('issue')->select();
		$this->assign('issue',$issue);
		return $this->fetch();
	}
	
	public function run_notcount(){
		if (!request()->isAjax()) $this->error('操作失败');
		$order_id = intval($this->request->post('orderId'));
		$issue = db('issue')->where(array('id' => $this->request->post('type')))->find();
		//$issue['type'] 1: 订单不结算配送原因 2: 更换配送员原因
		$data = array(
			'orderid' => $order_id,
			'type' => $this->request->post('type'),
			'uid' => $this->request->post('uid'),
			'admin_uid' => $this->userinfo['id'],
			'content' => $this->request->post('content'),
			'status' => 0,
			'time' => time(),
		);
		if ($data['content'] == '') $this->ajaxReturn(array('code' => 0,'msg' => '请输入消息内容'));
		if ($issue['type'] == 1){
			db('delivery_order')->where(array('id' => $order_id))->setField('iscount',2);
		}else{
			db('delivery_order')->where(array('id' => $order_id))->setField('timeout',2);
		}
		if (db('user_msg')->insert($data)){
			$this->ajaxReturn(array('code' => 1,'msg' => '操作成功'));
		}else{
			$this->ajaxReturn(array('code' => 0,'msg' => '操作失败'));
		}
	}
	
	//正在配送
	public function index3(){
		$query_where = $this->query_where();
		$where = 'do.time > 0';
		$where = $this->query_string($where);
		$this->orderField = implode(',', $this->orderField).',do.id,do.userId as delivery_uid,do.deliverMoney,do.time,do.timeout,do.iscount';
		$totalRow = Db::query("SELECT COUNT(do.id) AS count FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.status=1 and $where");

		$data = Db::query("SELECT {$this->orderField} FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.status=1 and $where");
		$this->user($data);
		$this->assign('lists',$data);
		$this->assign('page','');
		return $this->fetch('index2');
	}
	
	//已配送，未确认
	public function index4(){
		$query_where = $this->query_where();
		$where = 'do.time > 0';
		$where = $this->query_string($where);
		$this->orderField = implode(',', $this->orderField).',do.id,do.userId as delivery_uid,do.deliverMoney,do.time,do.timeout,do.iscount';
		$totalRow = Db::query("SELECT COUNT(do.id) AS count FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.status=2 and $where");
		$data = Db::query("SELECT {$this->orderField} FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.status=2 and $where");
		$this->user($data);
		$this->assign('lists',$data);
		$this->assign('page','');
		$this->assign('not_handler',true);
		return $this->fetch('index2');
	}
	
	//已完成
	public function finish(){
		$query_where = $this->query_where();
		$where = 'do.time > 0';
		$where = $this->query_string($where);
		$this->orderField = implode(',', $this->orderField).',do.id,do.userId as delivery_uid,do.deliverMoney,do.time,do.timeout,do.iscount';
		$totalRow = Db::query("SELECT COUNT(do.id) AS count FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.status=3 and $where");
		
		$data = Db::query("SELECT {$this->orderField} FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.status=3 and $where");
		$this->user($data);
		$this->assign('lists',$data);
		$this->assign('page','');
		$this->assign('not_handler',true);
		$this->assign('not_show',true);
		return $this->fetch('index2');
	}
	
	public function cancel(){
		$query_where = $this->query_where();
		$where = 'do.time > 0';
		$where = $this->query_string($where);
		$this->orderField = implode(',', $this->orderField).',do.id,do.userId as delivery_uid,do.deliverMoney,do.time,do.timeout,do.iscount';
		$totalRow = Db::query("SELECT COUNT(do.id) AS count FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.iscancel=1 and $where");

		$data = Db::query("SELECT {$this->orderField} FROM {$this->oto_db_prefix}orders AS o INNER JOIN {$this->default_config['database']}.{$this->pt_table_prefix}delivery_order AS do ON do.orderId=o.orderId WHERE do.iscancel=1 and $where");
		$this->user($data);
		$this->assign('lists',$data);
		$this->assign('page','');
		$this->assign('not_handler',true);
		$this->assign('not_show',true);
		return $this->fetch('index2');
	}
		
	//订单详情
	public function detail(){
		$this->assign('not_layout',true);
		$orderId = $this->request->param('orderid');
		if (!$orderId) $this->error('订单不存在');
		$orderInfo = $this->db->name('orders')->where(array('orderId' => $orderId))->find();
		if (!$orderInfo) $this->error('订单不存在');
		$this->assign($orderInfo);
		$shop = $this->db->name('shops')->where(array('shopId' => $orderInfo['shopId']))
		->field(array('shopImg','shopTel','userId','shopName','shopAddress','latitude','longitude'))->find();
		$this->assign($shop);
		$coupon = $this->db->name('youhui')->where(['id' => $orderInfo['couponId']])->find();
		$this->assign('coupon',$coupon);
		$orderGoods = $this->db->name('order_goods')->where(array('orderId' => $orderId))->select();
		$this->assign('lists',$orderGoods);
		$deliverInfo = db('delivery_order')->where(array('orderId' => $orderId,'user_send' => 0))->find();
		$isData = db('user_msg')->where(array('orderid' => $deliverInfo['id']))->find();
		$this->assign('isData',$isData);
		return $this->fetch();
	}
	
	//派单
	public function send_order(){
		$this->assign('not_layout',true);
		$orderId = $this->request->param('orderid');
		if (!$orderId) $this->error('订单不存在');
		$orderInfo = $this->db->name('orders')->where(array('orderId' => $orderId))->find();
		if (!$orderInfo) $this->error('订单不存在');
		//派单平台设置商家配送区域
		$shop_section = db('set_section')->where(array('shopId' => $orderInfo['shopId']))->find();
		//符合的配送员和配送地区
		$user = db('user_section')->where(array('section_id' => array('in',$shop_section['section'])))->select();
		$userids = '';
		$address_ids = array();
		foreach ($user as $key => $value){
			$address_ids[] = $value['section_id'];
			$userids .= $value['uid'].',';
		}
		$address_section = array();
		if (!empty($userids)){
			$address_section = db('address_section')->where(array('id' => array('IN',$address_ids)))->select();
		}
		$userlists = db('user')->where(array('status' => 1,'check_status' => 1,'id' => array('IN',rtrim($userids,','))))->field(array('id','username','truename','mobile','user_face'))->select();
		$this->assign('userlist',$userlists);
		$this->assign('orderInfo',$orderInfo);
		return $this->fetch();
	}
	
	//派单到配送
	public function send_order_run(){
		if (!request()->isAjax()) $this->error('操作失败');
		$order_id = intval($this->request->post('orderId'));
		$shop_id = intval($this->request->post('shopId'));
		$user_id = intval($this->request->post('user_id'));
		if (!$user_id) $this->ajaxReturn(array('code' => 0,'msg' => '请选择配送员'));
		$user = db('user')->where(array('id' => $user_id,'status' => 1,'check_status' => 1))->field(array('id','mobile'))->find();
		if (empty($user)) $this->ajaxReturn(array('code' => 0,'msg' => '配送员不存在'));
		$map = array('shopId' => $shop_id,'orderId' => $order_id);
		$orderInfo = $this->db->name('orders')->where($map)->find();
		if (empty($orderInfo)) $this->ajaxReturn(array('code' => 0,'msg' => '订单不存在'));
		$delivery_order = db('delivery_order');
		$inOrder = $delivery_order->where($map)->count();
		if ($inOrder > 0) $this->ajaxReturn(array('code' => 0,'msg' => '订单已派单'));
		$insertData = array(
			'userId' => $user['id'],
			'shopId' => $orderInfo['shopId'],
			'orderId' => $orderInfo['orderId'],
			'status' => 0,
			'time' => time(),
		);
		$delivery_order_id = $delivery_order->insertGetId($insertData) ? array('code' => 1,'msg' => '派单成功') : array('code' => 0,'msg' => '派单失败');
		if ($delivery_order_id) {
			$this->db->name('orders')->where($map)->setField('orderStatus',5);
			$user_mobile = $user['mobile'];

			// 旧
			// $orderId = $orderInfo['orderId'];
			// 唐峰康改 推送消息 跳转APP详情页必须是 delivery_order里 的主键id
			$orderId = $delivery_order_id;
			
			require $_SERVER['DOCUMENT_ROOT'] . '/vendor/' . 'JpushSend.class.php';
			
			$receive['alias'][] = $user_mobile;
			$chattitle = '新信息';
			$content = '您有新的订单';
			$content = $chattitle . ":" . $content;
			$fetion = new \JpushSend();
			$m_type = 'paotui';
			$m_txt = array('orderId' => $orderId);
			$m_time = '600'; //默认
			$res = $fetion->sendPub($receive, $content, $m_type, $m_txt, $m_time);
		}
		
		$this->ajaxReturn($data);
	}
	
}